package com.kye.express.business.tcl.home;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;

import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.base.utils.NetworkMonitorUtils;
import com.kye.express.R;
import com.kye.express.business.base.BaseToolbarActivity;
import com.kye.express.business.login.LoginActivity;
import com.kye.express.business.tcl.detail.TCLDetailActivity;
import com.kye.express.databinding.ActivityTclBinding;
import com.kye.express.view.ToastManager;
import com.kye.express.view.reclyerview.GridSpacingItemDecoration;
import com.kye.model.base.PageInfo;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.tcl.ResponseTCLGoodsListBean;
import com.kye.model.bean.user.User;
import com.kye.model.constant.Constants;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.List;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * TCL首页 Activity
 * <p>
 * Created by SkyYu on 2018/2/1
 */
public class TCLActivity extends BaseToolbarActivity implements TCLContract.TCLView, TCLItemViewBinder.OnGoodsItemListener {

    private static final String TAG = TCLActivity.class.getSimpleName();

    private ActivityTclBinding mBinding;
    private TCLContract.TCLPresenter mPresenter;
    private MultiTypeAdapter mAdapter;

    private String phone = "";
    private int pageIndexDefault = 1;
    public int pageIndex = PageInfo.INDEX_DEFAULT;
    private int pageSize = PageInfo.SIZE_DEFAULT;

    public static void startActivity(Context context) {
        context.startActivity(new Intent(context, TCLActivity.class));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initViews();
        initEvent();
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mPresenter) mPresenter.unbind();
    }

    private void initViews() {
        initDataBinding();
        initPresenter();
        initToolbar();
    }

    private void initDataBinding() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_tcl);
    }

    private void initToolbar() {
        setUpToolbar(mBinding.toolbarTcl);
        setTitle(getString(R.string.tcl_title));
    }

    private void initData() {
        initAdapter();
    }

    private void initPresenter() {
        mPresenter = new TCLContract.TCLPresenter();
        mPresenter.bind(this);
    }

    private void initAdapter() {
        mAdapter = new MultiTypeAdapter();
        mAdapter.register(ResponseTCLGoodsListBean.DatasBean.class, new TCLItemViewBinder(this));
        mAdapter.setItems(new Items());
        mBinding.recyclerviewTcl.setLayoutManager(new GridLayoutManager(this, 2));
        mBinding.recyclerviewTcl.addItemDecoration(new GridSpacingItemDecoration(2, 5, false));
        mBinding.recyclerviewTcl.setItemAnimator(new DefaultItemAnimator());
        mBinding.recyclerviewTcl.setAdapter(mAdapter);
    }

    private void initEvent() {
        mBinding.statusLayoutTcl.setOnLoadingListener(() ->
                request(true, false, false, phone, pageIndex, pageSize)
        );

        mBinding.smartrefreshlayoutTcl.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                request(false, true, false, phone, pageIndexDefault, pageSize);
            }

            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                request(false, false, true, phone, pageIndex, pageSize);
            }
        });

        RxView.clicks(mBinding.llEmpty.btEmptyRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<>())
                .subscribe((Object) -> {
                    mBinding.statusLayoutTcl.showLoadingView();
                    request(false, true, false, phone, pageIndexDefault, pageSize);
                });
        RxView.clicks(mBinding.llErrorNet.btErrorNetRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<>())
                .subscribe((Object) -> {
                    mBinding.statusLayoutTcl.showLoadingView();
                    request(false, true, false, phone, pageIndexDefault, pageSize);
                });
        RxView.clicks(mBinding.llErrorServer.btErrorServerRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<>())
                .subscribe((Object) -> {
                    mBinding.statusLayoutTcl.showLoadingView();
                    request(false, true, false, phone, pageIndexDefault, pageSize);
                });
    }

    private void request(boolean isFirstIn, boolean isReFresh, boolean isLoadMore, String phone, int pageIndex, int pageSize) {
        NetworkMonitorUtils.networkObservable(this)
                .compose(this.bindToLifecycleDestroy())
                .map((connectivity) -> {
                    NetworkInfo.State state = connectivity.getState();
                    switch (state) {
                        case CONNECTED:
                        case CONNECTING:
                            return true;
                        case DISCONNECTED:
                        case DISCONNECTING:
                            return false;
                        default:
                            return false;
                    }
                })
                .subscribe((Boolean) -> {
                    if (Boolean) {
                        mPresenter.requestToJDGoodsList(isFirstIn, isReFresh, isLoadMore, phone, pageIndex, pageSize);
                    } else {
                        mBinding.statusLayoutTcl.showErrorNetworkView();
                        ToastManager.show(this, getString(R.string.common_net_error));
                    }
                });
    }

    void resetCurrentPageIndex() {
        setCurrentPageIndex(1);
    }

    void setCurrentPageIndex(int currentPage) {
        pageIndex = currentPage;
    }

    @Override
    public void onLoadUser(User user) {
        if (user == null || !user.isLogin()) {
            ToastManager.show(this, getString(R.string.common_login));
            LoginActivity.startActivity(this);
        } else {
            phone = user.getPhone();
            mBinding.statusLayoutTcl.showLoadingView();
        }
    }

    @Override
    public void onCompleteTCLGoodsList(boolean isLoadMore) {
        if (isLoadMore) {
            mBinding.smartrefreshlayoutTcl.finishLoadmore();
        } else {
            mBinding.smartrefreshlayoutTcl.finishRefresh();
        }
    }

    @Override
    public void onSuccessTCLGoodsList(OpenApiResult<ResponseTCLGoodsListBean> bean, boolean isFirstIn, boolean isReFresh, boolean isLoadMore) {
        if (bean != null) {
            if (bean.getCode() == Constants.ResponseCode_SUCCESS) {
                List<ResponseTCLGoodsListBean.DatasBean> tempData = bean.getData().getDatas();
                if (tempData.size() > 0) {
                    mBinding.statusLayoutTcl.showContentView();
                    Items data = (Items) mAdapter.getItems();
                    if (!isLoadMore) {
                        data.clear();
                        data.addAll(tempData);
                        mAdapter.setItems(data);
                        mAdapter.notifyDataSetChanged();
                    } else {
                        data.addAll(tempData);
                        int start = tempData.size();
                        mAdapter.notifyItemRangeChanged(start, data.size());
                    }
                    if (isReFresh) {
                        resetCurrentPageIndex();
                    }
                    setCurrentPageIndex(pageIndex + 1);
                } else {
                    if (isFirstIn) {
                        mBinding.statusLayoutTcl.getEmptyTextView();
                    } else {
                        ToastManager.show(this, getString(R.string.common_no_more_datas));
                    }
                }
                if (tempData.size() < pageSize) {
                    mBinding.smartrefreshlayoutTcl.setEnableLoadmore(false);
                }
            } else {
                if (isLoadMore) {
                    ToastManager.show(this, getString(R.string.common_no_more_datas));
                } else {
                    ToastManager.show(this, bean.getMsg());
                }
            }
        } else {
            Logger.d(TAG + " - onSuccessTCLGoodsList - bean is null");
        }
    }

    @Override
    public void onApiErrorTCLGoodsList(OpenApiResult<ResponseTCLGoodsListBean> result, int code, String msg) {
        mBinding.statusLayoutTcl.showErrorServerView();
        ToastManager.show(this, msg);
        Logger.d(TAG + " - onApiErrorTCLGoodsList - result:" + result + ",code:" + code + ",msg:" + msg);
    }

    @Override
    public void onOtherErrorTCLGoodsList(Throwable e) {
        mBinding.statusLayoutTcl.showErrorNetworkView();
        ToastManager.show(this, getString(R.string.common_net_error));
        Logger.d(TAG + " - onOtherErrorTCLGoodsList : " + e.getMessage());
        e.printStackTrace();
    }

    @Override
    public void onGoodsItemClicked(ResponseTCLGoodsListBean.DatasBean item) {
        TCLDetailActivity.startActivity(this, phone, String.valueOf(item.getGoodsId()), (ArrayList<String>) item.getUrlAddress());
    }
}